﻿#region 程序集 VanillaPsycastsExpanded, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null
// C:\code\MyMod\MOD\bin\this!!!!!!!1\1.4\Assemblies\VanillaPsycastsExpanded.dll
// Decompiled with ICSharpCode.Decompiler 7.1.0.6543
#endregion

using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using RimWorld;
using RimWorld.BaseGen;
using RimWorld.QuestGen;
using RimWorld.SketchGen;
using UnityEngine;
using Verse;
using Verse.Noise;
using RimWorld.BaseGen;
using ResolveParams = RimWorld.BaseGen.ResolveParams;
using RimWorld.Planet;
using Verse.AI.Group;
using Verse.AI;
using RI_Talisman;
using Verse.Sound;

namespace WhoXiuXian
{
    public class RI_Building_AncientCultivatorCryptosleepCasket : Building
    {

        private List<Pawn> tmpPawnsCanReach = new List<Pawn>();

        private List<IntVec3> tmpObservationSpots = new List<IntVec3>();

        public bool CanActivateNow = true;

        public bool Activated = false;

        long tickToActive = 0;

        List<IntVec3> listToSpawn = new List<IntVec3>();

        List<Thing> listThingToSpawn = new List<Thing>();

        List<Pawn> pawnsSpawned = new List<Pawn>();
        private TargetInfo EffecterInfo => new TargetInfo(this.Position, this.Map);


        public override IEnumerable<Gizmo> GetGizmos()
        {
            foreach (Gizmo gizmo in base.GetGizmos())
            {
                yield return gizmo;
            }

            if (DebugSettings.ShowDevGizmos)
            {
                Command_Action command_Action = new Command_Action();
                command_Action.action = Activate;
                command_Action.Disabled = !CanActivateNow;
                command_Action.defaultLabel = "DEV: Activate";
                yield return command_Action;
            }
        }

        public void Activate()
        {
            if (!Activated)
            {
                Activated = true;
                List<IntVec3> list = RI_RandomUtility.GetCircularRegion(this.InteractionCell, 12);
                List<IntVec3> listClose = RI_RandomUtility.GetCircularRegion(this.InteractionCell, 3);

                foreach (IntVec3 pos in listClose)
                {
                    list.Remove(pos);
                }
                listToSpawn = list.ListFullCopy();
                foreach (IntVec3 pos in list)
                {
                    if (pos.GetTerrain(this.Map) != RI_T_DefOfs.RI_Building_AncientFloorA)
                    {
                        listToSpawn.Remove(pos);
                    }
                }
            }
        }
        public override void Tick()
        {
            if (Activated)
            {
                tickToActive++;

                if (tickToActive % 20 == 0 && tickToActive <= 160)
                {
                    IntVec3 intVec3 = listToSpawn.RandomElement();
                    if (intVec3.GetFirstItem(this.Map) == null)
                    {
                        listThingToSpawn.Add(GenSpawn.Spawn(RI_T_DefOfs.RI_SteelPuppetTrap, intVec3, this.Map));
                        SoundDefOf.MetalHitImportant.PlayOneShot(new TargetInfo(intVec3, this.Map));
                    }
                }

                if (tickToActive >= 200 && CanActivateNow)
                {
                    //傀儡
                    foreach (Thing thing in listThingToSpawn)
                    {
                        Pawn puppet = PawnGenerator.GeneratePawn(new PawnGenerationRequest(Random.Range(0, 100) > 50 ? RI_T_DefOfs.RI_AncientPuppetA : RI_T_DefOfs.RI_AncientPuppetB
                            , Faction.OfAncientsHostile,
                            PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, 0f, false, true, false, false,
                            true, false, false, false, false, 0f, 0f, null, 0f, null, null, null, null, null, null, null, null,
                            null, null, null, null, true, true, true));
                        pawnsSpawned.Add((Pawn)(GenSpawn.Spawn(puppet, thing.Position, this.Map, Rot4.Random)));
                        if (!thing.Destroyed)
                        {
                            thing.Destroy();
                        }
                    }
                    //人
                    Pawn pawn = (Pawn)GenSpawn.Spawn(GeneratePawn(), this.Position, this.Map, Rot4.Random);
                    pawnsSpawned.Add(pawn);
                    pawn.SetFaction(Faction.OfAncientsHostile);
                    pawn.health.AddHediff(RI_T_DefOfs.RI_AncientCultivatorHediff);
                    pawn.skills.GetSkill(SkillDefOf.Melee).Level = 20;
                    if (pawn.apparel.CanWearWithoutDroppingAnything(RI_T_DefOfs.RI_Apparel_AncientCultivatorArmor)) {
                        pawn.apparel.Wear((Apparel)GenSpawn.Spawn(RI_T_DefOfs.RI_Apparel_AncientCultivatorArmor,pawn.Position,pawn.Map));
                    }
                    if (pawn.apparel.CanWearWithoutDroppingAnything(RI_T_DefOfs.RI_Apparel_AncientCultivatorHelmet))
                    {
                        pawn.apparel.Wear((Apparel)GenSpawn.Spawn(RI_T_DefOfs.RI_Apparel_AncientCultivatorHelmet, pawn.Position, pawn.Map));
                    }
                    LordJob_DefendPoint lordJob = new LordJob_DefendPoint(this.Position);
                    Lord lord = LordMaker.MakeNewLord(Faction.OfAncientsHostile, lordJob, this.Map);
                    lord.AddPawns(pawnsSpawned);
                    //其他
                    CanActivateNow = false;
                    FleckCreationData dataStatic2 = FleckMaker.GetDataStatic(Position.ToVector3(), Map, FleckDefOf.ExplosionFlash, 1);
                    dataStatic2.rotation = 0f;
                    dataStatic2.velocitySpeed = Rand.Range(90f, 99f);
                    Map.flecks.CreateFleck(dataStatic2);
                    if (ModLister.AnomalyInstalled)
                    {
                        EffecterDefOf.MonolithLevelChanged.Spawn().Trigger(EffecterInfo, EffecterInfo);
                    }
                    string text = string.Format("一名强大的古修者从建筑中跃出，因为你搅扰了他的安眠而极度愤怒！").Translate();
                    ChoiceLetter choiceLetter = LetterMaker.MakeLetter("古修者出现".Translate(), text, LetterDefOf.ThreatBig);
                    Find.LetterStack.ReceiveLetter(choiceLetter);
                    GenSpawn.Spawn(RI_T_DefOfs.RI_Building_AncientCryoCapsuleRuin, this.Position, this.Map);
                    if (!this.Destroyed)
                    {
                        this.Destroy();
                    }
                }
            }
        }
        protected void SendStandardLetter(TaggedString baseLetterLabel, TaggedString baseLetterText, LetterDef baseLetterDef, IncidentParms parms, LookTargets lookTargets, params NamedArgument[] textArgs)
        {
            RI_RandomUtility.SendIncidentLetter(baseLetterLabel, baseLetterText, baseLetterDef, parms, lookTargets, IncidentDefOf.RaidEnemy, textArgs);
        }
        public override void PreApplyDamage(ref DamageInfo dinfo, out bool absorbed)
        {
            if (!Activated)
            {
                Activated = true;
            }
            absorbed = true;
        }

        protected Pawn GeneratePawn()
        {
            var pawn = PawnGenerator.GeneratePawn(new PawnGenerationRequest(RI_T_DefOfs.RI_Pawn_AncientCultivator, Faction.OfAncientsHostile,
               PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, 0f, false, true, false, false,
               true, false, false, false, false, 0f, 0f, null, 0f, null, null, null, null, null, null, null, null,
               null, null, null, null, false, true, true));
            return pawn;
        }

        public override IEnumerable<FloatMenuOption> GetMultiSelectFloatMenuOptions(List<Pawn> selPawns)
        {
            if (!CanActivateNow)
            {
                yield return new FloatMenuOption("CannotInvoke".Translate("AncientCultivator".Translate()) + ": " + "AlreadyInvoked".Translate(), null);
                yield break;
            }

            tmpPawnsCanReach.Clear();
            for (int i = 0; i < selPawns.Count; i++)
            {
                if (selPawns[i].CanReach(this, PathEndMode.InteractionCell, Danger.Deadly))
                {
                    tmpPawnsCanReach.Add(selPawns[i]);
                }
            }

            if (tmpPawnsCanReach.NullOrEmpty())
            {
                yield return new FloatMenuOption("CannotInvoke".Translate("AncientCultivator".Translate()) + ": " + "NoPath".Translate().CapitalizeFirst(), null);
                yield break;
            }

            yield return new FloatMenuOption("Invoke".Translate("AncientCultivator".Translate()), delegate
            {
                tmpPawnsCanReach[0].jobs.TryTakeOrderedJob(JobMaker.MakeJob(RI_T_DefOfs.RI_JobDriver_ActivateAncientCultivatorCryptosleepCasket, this), JobTag.Misc);
                tmpObservationSpots.Clear();
                IntVec3 intVec = base.Position + ((InteractionCell - base.Position).ToVector3().normalized * 8f).ToIntVec3();
                for (int j = 1; j < tmpPawnsCanReach.Count; j++)
                {
                    IntVec3 intVec2 = RCellFinder.BestOrderedGotoDestNear(intVec, tmpPawnsCanReach[j], (IntVec3 c) => !tmpObservationSpots.Contains(c));
                    FloatMenuMakerMap.PawnGotoAction(intVec, tmpPawnsCanReach[j], intVec2);
                    tmpObservationSpots.Add(intVec2);
                }

                tmpObservationSpots.Clear();
            });
        }
    }
}